﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LPLS.Commons.DynamicOP
{
    /// <summary>
    /// 动态对象帮助类
    /// </summary>
    public static class DynamicHelper
    {
        /// <summary>
        /// 获取动态对象的属性名称列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static IEnumerable<string> GetPropertyNames(dynamic obj)
        {
            if (obj is IDictionary<string, object> dict)
                return dict.Keys;

            // 处理其他动态类型
            return ((Type)obj.GetType()).GetProperties().Select(p => p.Name);
        }
        /// <summary>
        /// 获取动态对象的属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static object GetPropertyValue(dynamic obj, string propertyName)
        {
            if (obj is IDictionary<string, object> dict && dict.TryGetValue(propertyName, out var value))
                return value;

            // 处理其他动态类型
            return ((Type)obj.GetType()).GetProperty(propertyName)?.GetValue(obj);
        }
    }
}
